<!--
 * @Author: hpc(hepch)
 * @Date: 2021-05-21 15:05:09
 * @LastEditors: 予程_hepch
 * @LastEditTime: 2022-04-13 14:58:51
 * @Description:filecontent
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div>
    <div v-show="visible" style="margin-top: 10px">
      <a-divider>车辆定位轨迹查询</a-divider>
      <a-form class="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <a-form-item label="车牌">
          <!-- <a-input placeholder="车牌号" v-model="vehicleID"></a-input> -->
          <a-select
            show-search
            autoFocus
            v-model="vehicleID"
            placeholder="输入车牌模糊查询"
            style="width: 200px"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="handleLicenseChange"
          >
            <a-select-option v-for="d in licenseList" :key="d.value">
              {{ d.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="颜色">
          <!-- <a-select
						show-search
						placeholder="选择颜色"
						v-model="plateColor"
						style="width: 100%"
						@change="handleChange"
						@select="selectPlateColor"
						allowClear
						disabled
					>
						<a-select-option v-for="item in filteredOptions" :key="item" :value="item">
							{{ item }}
						</a-select-option>
					</a-select> -->

          <a-input
            placeholder="车牌颜色"
            v-model="plateColor"
            disabled
          ></a-input>
        </a-form-item>
        <a-form-item label="时间">
          <a-date-picker
            v-model="startTime"
            :disabled-date="disabledStartDate"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间(轨迹查询必选)"
            @openChange="handleStartOpenChange"
          />
          <a-date-picker
            v-model="endTime"
            :disabled-date="disabledEndDate"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间(轨迹查询必选)"
            :open="endOpen"
            @openChange="handleEndOpenChange"
          />
        </a-form-item>

        <a-button class="search-location" type="primary" @click="searchLocation"
          >定位</a-button
        >
        <a-button
          class="search-track"
          type="primary"
          @click="searchTrack"
          :disabled="disableButTrack"
          >轨迹</a-button
        >
        <a-button class="search-clear" type="default" @click="clearTrack"
          >清除
        </a-button>
      </a-form>
      <a-divider style="margin-top: 100px" v-if="false"
        >某类型车辆实时位置</a-divider
      >
      <a-form
        class="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        v-if="false"
      >
        <a-form-item label="类型">
          <a-select
            show-search
            placeholder="搜索选择车辆类型"
            v-model="vehicleType"
            style="width: 100%"
            @change="changeVehicleType"
            allowClear
          >
            <a-select-option
              v-for="item in filteredType"
              :key="item"
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="车辆归属地">
          <a-input placeholder="车辆归属地" v-model="vehAreaCode"></a-input>
        </a-form-item>
        <a-form-item label="车辆当前所在区域"
          ><a-input
            placeholder="车辆当前所在区域"
            v-model="curAreaCode"
          ></a-input
        ></a-form-item>

        <a-button
          class="search-location"
          type="primary"
          @click="searchATypeVehicleLocation"
          >定位</a-button
        >
        <a-button class="search-track" type="defult">重置</a-button>
      </a-form>
    </div>
    <vehicle-track-result ref="VehicleTrackResult" />
  </div>
</template>

<script>
import VehicleTrackResult from "./VehicleTrackResult.vue";
import services from "@/services/api";
import { plateColorkeyValue } from "@/utils/plateColormapping";
import { vehicleTypekeyValue } from "@/utils/vehicleTypeMap";
// import { transformWGS84ToGCJ02 } from "@/utils/CoordinateTransform";
//import elasticsearch from 'elasticsearch'

//import axios from 'axios'
const plateColors = [
  "蓝色",
  "黄色",
  "黑色",
  "白色",
  "其他",
  "农黄",
  "农绿",
  "农蓝",
];
const vehicleTypes = [
  "邮政快递车辆",
  "道路集卡货物运输",
  "旅游客运",
  "路政执法车辆",
  "班车客运",
  "包车客运",
  "道路普通货物运输",
  "道路危险货物运输",
  "机动车驾驶员培训（教练车)",
  "国际道路运输",
  "公交运输",
  "出租运输",
  "其他",
  "应急车辆",
  "行政用车",
  "机械车辆",
  "人员运输",
  "网约出租运输",
  "道路普通货物运输（12吨）",
];
import moment from "moment";
// import L from "leaflet";
export default {
  components: { VehicleTrackResult },
  data() {
    return {
      startTime: null,
      endTime: null,
      endOpen: false,
      visible: true,
      vehicleID: "",
      plateColor: "",
      vehicleType: "公交运输",
      vehAreaCode: "",
      curAreaCode: "",
      licenseList: [],
      vehicleInfo: undefined,
    };
  },
  mounted() {
    this.endTime = moment();
    this.startTime = moment().subtract(3, "days");
  },
  computed: {
    filteredOptions() {
      return plateColors;
    },
    filteredType() {
      return vehicleTypes;
    },
    vehicleTrackGroup() {
      return this.$store.state.vehicleTrackGroup;
    },

    vehicleLocationGroup() {
      return this.$store.state.vehicleLocationGroup;
    },
    disableButTrack() {
      if (this.startTime && this.endTime) {
        return false;
      } else {
        return true;
      }
    },
  },
  methods: {
    changeVehicleType() {},
    /**
     * @description: 车牌输入变化调用模糊查询
     * @param {*}
     * @return {*}
     */

    handleSearch: function (value) {
      this.fetch(value);
    },
    /**
     * @description: 模糊查询
     * @param {*}
     * @return {*}
     */

    fetch: function (value) {
      let self = this;

      this.licenseList = [];
      if (this.timeout) {
        clearTimeout(this.timeout);
        this.timeout = null;
      }

      function fake() {
        self.esSearch(value);
      }

      this.timeout = setTimeout(fake, 300);
    },
    /**
     * @description: 选中车牌
     * @param {*} value
     * @return {*}
     */

    handleLicenseChange(value) {
      this.vehicleID = value;
      for (let i in this.licenseList) {
        let item = this.licenseList[i];
        if (item.value == this.vehicleID) {
          this.vehicleInfo = item.info;
          this.selectPlateColor(item.info["PLATE_COLOR"]);
        }
      }
    },
    /**
     * @description: 选中车辆类型
     * @param {*} selected
     * @return {*}
     */

    changevehicleType(selected) {
      this.vehicleType = vehicleTypekeyValue(selected);
    },
    /**
     * @description: 选中车牌颜色
     * @param {*} selecteditem
     * @return {*}
     */
    selectPlateColor(value) {
      this.plateColor = value;
    },
    handleChange(selecteditem) {
      this.plateColor = selecteditem;
      console.log(this.plateColor);
    },
    esParam(currentvalue) {
      let querybody = {
        query: {
          bool: {
            must: [
              {
                wildcard: {
                  "VEH_LICENSE.keyword": {
                    value: "*" + currentvalue + "*",
                  },
                },
              },
              {
                match: {
                  VEH_STATUS: "营运",
                },
              },
            ],
          },
        },
      };
      return querybody;
    },
    esSearch(currentvalue) {
      let that = this;
      let esParam = this.esParam(currentvalue);
      services
        .searchVehicleInfo(esParam)
        .then((res) => {
          let items = res.hits.hits;
          let thatt = that;
          console.log("返回模糊查询结果", res.hits.hits);
          items.forEach((item) => {
            thatt.licenseList.push({
              value: item._source["VEH_LICENSE"],
              text: item._source["VEH_LICENSE"],
              info: item._source,
            });
          });

          self.vehicleInfo = {};
        })
        .catch((err) => {
          self.vehicleInfo = {};
          console.log(err);
        });
    },
    /**
     * @description: 获取选中的车辆信息
     * @param {*} vehicle
     * @return {*}
     */

    buidSearchParam(vehicle) {
      this.vehicleTrackGroup.clearLayers();
      this.vehicleLocationGroup.clearLayers();
      this.vehicleID = vehicle.VEH_LICENSE;
      this.plateColor = vehicle.PLATE_COLOR;
      this.vehicleInfo = vehicle;
    },
    disabledStartDate(startTime) {
      const endTime = this.endTime;
      if (!startTime || !endTime) {
        return false;
      }
      return startTime.valueOf() > endTime.valueOf();
    },
    disabledEndDate(endTime) {
      const startTime = this.startTime;
      if (!endTime || !startTime) {
        return false;
      }
      return startTime.valueOf() >= endTime.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },

    searchATypeVehicleLocation() {
      let param = this.setSearchParam("vehicellocation");
      let self = this;
      services
        .searchVehicleTypeLocation(param)
        .then((res) => {
          console.log("定位gps", res.tollList);
          if (res.tollList.length == 0) {
            self.$message.info("未查询到定位数据");
            return;
          }
          self.$refs.VehicleTrackResult.markAtypeVehicles(
            res.tollList,
            self.vehicleInfo
          );
        })
        .catch((err) => {
          self.$message.info("查询失败");
          console.log("error", err);
        });
    },
    /**
     * @description: 定位查询入口
     * @param {*}
     * @return {*}
     */

    searchLocation() {
      let param = this.setSearchParam("location");
      // console.log(transformWGS84ToGCJ02(111.03484260657661, 27.1345656));
      // let lng = transformWGS84ToGCJ02(111.03484260657661, 27.1345656);
      // L.marker([lng[1], lng[0]]).addTo(this.vehicleTrackGroup);
      // L.marker([27.1345656, 111.03484260657661]).addTo(this.vehicleTrackGroup);
      let self = this;
      services
        .searchVehicleLocation(param)
        .then((res) => {
          console.log("定位gps", res.tollList);
          if (res.tollList.length == 0) {
            self.$message.info("未查询到定位数据");
            return;
          }
          self.$refs.VehicleTrackResult.markVehicle(
            res.tollList[0],
            self.vehicleInfo
          );
        })
        .catch((err) => {
          self.$message.info("查询失败");
          console.log("error", err);
        });
    },
    /**
     * @description: 调用查询当前车辆的位置和轨迹信息接口
     * @param {*} param
     * @return {*}
     */
    searchTrack() {
      let param = this.setSearchParam("track");
      let self = this;

      services
        .searchVehicleTrack(param)
        .then((res) => {
          console.log("车辆轨迹数据", res);
          if (res.tollList.length == 0) {
            self.$message.info("未查询到轨迹数据");
            return;
          }
          self.$refs.VehicleTrackResult.drawTrack(res.tollList);
        })
        .catch((err) => {
          self.$message.info("查询失败");
          console.log("error", err);
        });
    },
    /**
     * @description:设置查询当前车辆历史轨迹数据的参数
     * @param {*}
     * @return {*}
     */

    setSearchParam(searchtype) {
      let querybody = {};
      let plateColorCode = plateColorkeyValue(this.plateColor);
      if (searchtype == "location") {
        querybody = {
          vehicleNo: this.vehicleID,
          plateColor: plateColorCode,
        };
      } else if (searchtype == "track") {
        let starttime = [];
        let endtime = [];

        starttime[1] = this.startTime.format("HH:mm:ss").toString();
        endtime[1] = this.endTime.format("HH:mm:ss").toString();
        starttime[0] = this.startTime.format("YYYY-MM-DD").toString();
        endtime[0] = this.endTime.format("YYYY-MM-DD").toString();
        console.log(endtime, starttime);
        querybody = {
          vehicleNo: this.vehicleID,
          plateColor: plateColorCode,
          startTime: starttime[0] + " " + starttime[1],
          endTime: endtime[0] + " " + endtime[1],
          // startTime: encodeURIComponent('2021-04-20 00:00:00'),
          // endTime: encodeURIComponent('2021-04-21 00:00:00'),
        };
      } else if (searchtype == "vehicellocation") {
        querybody = {
          serviceType: this.vehicleType,
          // vehAreaCode: this.vehAreaCode,
          // curAreaCode: this.curAreaCode,
        };
      }
      return querybody;
    },
    /**
     * @description:执行查询
     * @param {*}
     * @return {*}
     */
    doQueryData(param) {
      console.log(param);
    },
    /**
     * @description:处理查询到的数据
     * @param {*}
     * @return {*}
     */
    dealResult(data) {
      console.log("车辆定位数据", data);
    },
    clearTrack() {
      this.vehicleTrackGroup.clearLayers();
      this.vehicleLocationGroup.clearLayers();
      this.plateColor = "";
      this.licenseList = [];
      this.vehicleID = "";
      this.endTime = moment();
      this.startTime = moment().subtract(3, "days");
    },
  },
};
</script>

<style lang="less" scoped>
.form {
  .search-location {
    float: left;
    width: 30% !important;
  }
  .search-track {
    margin-left: 10px;
    width: 30% !important;
  }
  .search-clear {
    margin-left: 10px;
    width: 30% !important;
  }
}
</style>
